<template>
  <div>
    <div>
      <div class="searchForm">
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input
              v-model="params.name"
              placeholder="按关键字查找"
              class="block"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getList(1)"
              class="block"
              >查询</el-button
            >
            <el-button icon="el-icon-plus" class="block" @click="add"
              >增加</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="block"
              @click="removeMore"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="message">
        <el-table
          :data="rows"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="name" label="商品名称"> </el-table-column>
          <el-table-column prop="brandName" label="品牌"> </el-table-column>
          <el-table-column prop="imgs" label="轮播图片">
            <template slot-scope="scope">
              <img
                style="width: 40px; height: 40px"
                v-if="scope.row.imgs"
                :src="scope.row.imgs"
              />
            </template>
          </el-table-column>
          <el-table-column prop="sales" label="销量"> </el-table-column>
          <el-table-column prop="status" label="上架">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="statusChange(scope.row)"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定删除此数据吗？"
                @confirm="remove(scope.row)"
              >
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  style="margin-left: 20px"
                  size="mini"
                  slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          @size-change="sizeChange"
          @current-change="getList"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 100, 200, 300, 400]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="form._id ? '修改' : '新增'"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="400px"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播图片" prop="imgs" style="margin-bottom: 20px">
          <div
            @click="openFile"
            style="
              width: 100px;
              height: 100px;
              font-size: 32px;
              border: 1px dashed #ccc;
              text-align: center;
              line-height: 100px;
              opacity: 0.5;
              overflow: hiddrn;
            "
          >
            <img
              style="max-width: 100%; max-height: 100%"
              v-if="form.imgs"
              :src="form.imgs"
            />
            <span v-else>+</span>
          </div>
          <input
            ref="file"
            style="display: none"
            type="file"
            multiple
            accept="image/*"
            @change="changeFile"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="name" style="margin-bottom: 20px">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId" style="margin-bottom: 20px">
          <el-select v-model="form.brandId" placeholder="请选择品牌">
            <el-option
              v-for="(item, index) in rowes"
              :key="index"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销量" prop="sales" style="margin-bottom: 20px">
          <el-input type="text" v-model="form.sales"></el-input>
        </el-form-item>
        <el-form-item label="上架" prop="status" style="margin-bottom: 20px">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="changeSwitch"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canle">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import api from "@/api";
export default {
  name: "product",
  components: {
    //HelloWorld
  },
  data() {
    return {
      params: {
        name: "",
        brandId: "", //根据品牌和商品名称查询
        pageNum: 1,
        pageSize: 5,
      },
      rows: [],
      total: 0,
      dialogFormVisible: false,
      rowes: [], //存放所有启用的数据
      form: {
        _id: 0,
        name: "",
        brandId: "",
        imgs: "",
        sales: "",
        status: "",
        brandName: "",
      },
      rules: {
        imgs: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        name: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        brandId: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
      },
      selecteds: [],
      arry: {
        brandId: 0,
        brandName: "", ///用于缓存品牌项
      },
    };
  },
  methods: {
    //触发文件打开 点击加号
    openFile() {
      let fileElement = this.$refs.file;
      fileElement.click();
    },
    //监听上传文件事件
    changeFile(e) {
      let files = e.target.files;
      let formData = new FormData();
      formData.append("file", files[0]);
      this.$http({
        url: "upload",
        method: "POST",
        data: formData,
      }).then((res) => {
        if (res.filename)
          this.form.imgs = api.baseURL + "/uploads/" + res.filename;
        console.log(this.form);
      });
    },
    //关闭弹窗前的回调
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.getList(1);
          done();
        })
        .catch(() => {});
    },
    //取消弹窗刷新列表
    canle() {
      this.dialogFormVisible = false;
      this.getList(1);
    },
    //获取列表
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: "/admin/index/product",
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },
    //获取品牌列表i
    getBrandList() {
      this.$http({
        url: "/admin/index/brand",
      }).then((res) => {
        this.rowes = res.rows;
      });
    },
    //热门的开关
    hotChange(row) {
      this.$http({
        url: "/admin/index/product",
        method: "PUT",
        data: {
          indexId: row._id,
          hot: row.hot,
        },
      }).then((res) => {
        if (res.errorMsg) {
          this.getList();
        }
      });
    },
    //上架
    statusChange(row) {
      this.$http({
        url: "/admin/index/product",
        method: "PUT",
        data: {
          indexId: row._id,
          status: row.status,
        },
      }).then((res) => {
        if (res.errorMsg) {
          this.getList();
        }
      });
    },
    removeMore() {
      //获取选中的数据
      let checkedRowsPromse = [];
      let success = [],
        fail = [];
      for (let i = 0; i < this.selecteds.length; i++) {
        checkedRowsPromse.push(
          new Promise((resovle) => {
            let row = this.selecteds[i];
            this.$http({
              url: "/admin/index/product",
              method: "DELETE",
              params: { indexId: row._id },
            }).then((res) => {
              if (!res.errorMsg) {
                success.push(row._id);
              } else {
                fail.push(row._id);
              }
              resovle();
            });
          })
        );
      }
      ///删除
      Promise.all(checkedRowsPromse).then(() => {
        this.$message({
          message: `批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
          duration: 3000,
        });
        this.getList(1);
      });
    },
    //编辑时取消按钮改变页面显示值 解决办法 点击取消时 重新渲染一次页面
    cancel() {
      this.getList(1);
      this.dialogFormVisible = false;
    },
    handleSelectionChange(rows) {
      //存储选中数据
      this.selecteds = rows;
    },
    //修改pagesize
    sizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getList(1);
    },
    add() {
      //初始化
      this.form = {
        _id: 0,
        name: "",
        brandId: "",
        imgs: "",
        sales: "",
        status: "",
      };
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.form = row;
      this.arry.brandId = row.brandId;
      this.arry.brandName = row.brandName;
      this.form.brandId = row.brandName;
      this.dialogFormVisible = true;
    },
    //删除
    remove(row) {
      console.log(row);
      this.$http({
        url: "/admin/index/product",
        method: "DELETE",
        params: { indexId: row._id },
      }).then((res) => {
        if (!res.errorMsg) {
          this.getList(1);
        }
      });
    },
    //changeSwitch用于处理弹框的switch的值处理
    changeSwitch(res) {
      //0是不起用热门 1 是启用热门 默认是不启用的的
      this.form.status = res;
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (this.form.brandId == this.arry.brandName) {
          //没有更改品牌
          this.form.brandId = this.arry.brandId;
        }
        console.log(this.form);
        if (valid) {
          this.form.indexId = this.form._id;
          this.$http({
            url: "/admin/index/product",
            method: this.form.indexId ? "PUT" : "POST", //通过indeid判断是新增还是编辑
            data: this.form,
          }).then((res) => {
            if (!res.errorMsg) {
              this.dialogFormVisible = false;
              this.getList(this.form.indexId ? undefined : 1);
            }
          });
        }
      });
    },
  },
  created() {
    this.getList();
    this.getBrandList();
  },
  mounted() {},
};
</script>

<style >
</style>
